package com.educate.book.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.util.StringUtils;

import com.educate.book.model.bo.BookPageBO;
import com.educate.book.model.po.BookPage;
import com.educate.common.mongo.QueryUtils;

public class BookPageDaoImpl {

    @Resource MongoTemplate mongoTemplate;

    public Page<BookPage> query(BookPageBO bo, Pageable pageable) {
        List<Criteria> andCriteria = new ArrayList<>(10);
//        Criteria keyCriteria = QueryUtils.keyWord(keyWord, "qq", "wx", "tb");
//        if (keyCriteria != null) {
//            andCriteria.add(keyCriteria);
//        }
//        if (startTime != null || endTime != null) {
//            Criteria createTime = Criteria.where("createTime");
//            if (startTime != null) {
//                createTime.gt(startTime);
//            }
//            if (endTime != null) {
//                createTime.lt(endTime);
//            }
//            andCriteria.add(createTime);
//        }
        if (!StringUtils.isEmpty(bo.getISBN())) {
        	andCriteria.add(Criteria.where("ISBN").is(bo.getISBN()));
        }
        if (!StringUtils.isEmpty(bo.getBookId())) {
            andCriteria.add(Criteria.where("bookId").is(bo.getBookId()));
        }
        Query query = QueryUtils.query(andCriteria).with(pageable);
        query.with(new Sort(new Order(Direction.ASC, "pageNum")));
        List<BookPage> list = mongoTemplate.find(query, BookPage.class);
        return PageableExecutionUtils.getPage(list, pageable, () -> mongoTemplate.count(query, BookPage.class));

    }
}
